import type { ITestPaper, ITestItem } from '@/lib/test'
import { ref, computed, watchEffect } from 'vue'
import { useSetting, Setting } from '@/function/setting'
import { createTestSetterCloudStorage } from '@/lib/test'



export interface ISettingData {
    categorys: string[],
    levels: number[],
    num: number,
    random: boolean
}

export class TestController {

    status = ref<0 | 1>(0)

    testItems = ref<ITestItem[]>([])

    index = ref(0)

    currentTestItem = computed(() => this.testItems.value[this.index.value])

    messageList = ref<string[]>([])

    testSetter = createTestSetterCloudStorage()

    constructor(
        public paper: ITestPaper,
        public setting: Setting<ISettingData>
    ) {

        // 设置最后测试时间
        watchEffect(() => {
            const testItem = this.currentTestItem.value
            if (testItem) this.testSetter.setLastTime(testItem)
        })
    }

    reset() {
        this.status.value = 0
        this.index.value = 0
        this.testItems.value = []
    }

    start() {

        this.reset()
        this.createTextItems()
        this.status.value = 1
    }


    createTextItems() {

        const categorys = this.setting.get('categorys')
        const levels = this.setting.get('levels')
        const num = this.setting.get('num')
        const random = this.setting.get('random')

        // 筛选分类、等级
        let items = [...this.paper.items].filter(item => categorys.includes(item.category) && levels.includes(item.level))

        // 如果是随机排序
        if (random) {

            // 先按照lastTime排序
            items.sort((a, b) => a.lastTime - b.lastTime)

            // 按数量取出试题
            items = items.slice(0, num)

            // 再随机排序
            for (let i = 0; i < 10; i++)items.sort(() => random ? Math.random() - 0.5 : 0)

        }

        this.testItems.value = [...items]

    }


    prev() {
        if (this.status.value === 0) return
        if (this.index.value > 0) this.index.value--
    }

    next() {
        if (this.status.value === 0) return
        if (this.index.value < this.testItems.value.length - 1) this.index.value++
        else this.messageList.value.push('已完成所有题目')
    }



    setLevel(testItem: ITestItem, level: number) {

    }



}

export function useTestController(paper: ITestPaper) {

    const setting = useSetting<ISettingData>({
        categorys: paper.getCategorys(),
        levels: [0, 1, 2, 3, 4, 5],
        num: paper.items.length,
        random: false
    })

    const testController = new TestController(paper, setting)

    return {
        testController,
        setting
    }
}